package me.pinion.service;

import com.jfinal.core.Controller;
import me.pinion.Log;
import me.pinion.model.User;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public abstract class Service {
    protected Controller controller;
    private static Map<Class<? extends Service>, Service> INSTANCE_MAP = new HashMap<Class<? extends Service>, Service>();

    public static <Ser extends Service> Ser getInstance(Class<Ser> clazz){
        Ser service = (Ser) INSTANCE_MAP.get(clazz);
        if (service == null){
            try {
                service = clazz.newInstance();

                INSTANCE_MAP.put(clazz, service);

            } catch (InstantiationException e) {
                Log.e(e);
            } catch (IllegalAccessException e) {
                Log.e(e);
            }

            /**
             * Init service.filed
             */
            Field[] fields =service.getClass().getDeclaredFields();
            for (int i=0;i < fields.length; i++){
                Field field = fields[i];
                Class cla = field.getType();
                if(Service.class.isAssignableFrom(cla) && clazz != Service.class){
                    try {
                        service.setProperty(field.name, getInstance(cla))
                    } catch (IllegalAccessException e) {
                        Log.e(e);
                    }
                }
            }
        }

        return service;
    }
}
